<template>
  <el-dialog
    v-model="props.dialogVisible"
    :title="props.dialogForm?.title"
    :width="props.dialogForm?.width"
    :before-close="cancel"
    :show-close="true"
  >
    <div class="department">
      <el-row>
        <el-col :span="12">
          <el-input
            v-model="filterText"
            placeholder="可输入部门名称进行搜索"
            class="input"
          />
          <el-tree
            class="tree"
            ref="treeRef"
            :data="state.treeData"
            show-checkbox
            default-expand-all
            node-key="id"
            highlight-current
            :props="defaultProps"
            :default-checked-keys="checkTree"
            :filter-node-method="filterNode"
            @check="checkChange"
          />
        </el-col>
        <el-col :span="1">
          <el-divider direction="vertical" class="divider" />
        </el-col>

        <el-col :span="11" class="divide">
          <div class="box-selected">
            <h3 class="total">已选择（{{ state.selectedData.length }}）</h3>
            <div
              class="selected"
              v-for="(item, index) in state.selectedData"
              :key="item.id"
            >
              <span>{{ item.name }}</span>
              <el-icon :size="16" @click="deleteItem(item)" class="icon">
                <ele-CircleClose />
              </el-icon>
            </div>
          </div>
        </el-col>
      </el-row>
    </div>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="cancel()">取消</el-button>
        <el-button type="primary" @click="submitForm()"> 保存 </el-button>
      </span>
    </template>
  </el-dialog>
</template>
<script setup lang="ts">
import { ElMessage, FormInstance, FormRules, ElTree } from 'element-plus'
import { array } from 'snabbdom'
import {
  ref,
  reactive,
  defineAsyncComponent,
  watch,
  computed,
  onMounted
} from 'vue'
import { deptTreeList, setRight } from '/@/api/setting/index'

const props = defineProps({
  dialogVisible: Boolean,
  dialogForm: Object,
  dialogDetail: Object
})
const emit = defineEmits(['cancel', 'submit'])

const purFormRef = ref<FormInstance>()
const purForm = ref<any>({
  roleName: '',
  remark: ''
})

//输入框
const filterText = ref('')

//树组件
const state = reactive({
  //数组件原始数据
  treeData: [],
  //已选部门数据
  selectedData: [
    {
      id: '',
      name: ''
    }
  ],
  //所有部门数据
  allDepartment: [
    {
      id: '',
      name: ''
    }
  ]
})
const defaultProps = {
  children: 'children',
  label: 'deptName'
}
const checkTree = ref([''])
const treeRef = ref<InstanceType<typeof ElTree>>()

// 页面加载时
onMounted(() => {
  //   let params = { roleId: formId, terminalType: 1 }
  //   getTreeListPc(params)
})

const getTreeList = (params: any) => {
  checkTree.value = ['']
  state.selectedData = []
  state.treeData = []
  state.allDepartment = []
  deptTreeList().then((res) => {
    if (res.code == 0) {
      state.treeData = res.data
      filterAllSelected(state.treeData)
      checkedNodes(state.allDepartment)
    }
  })
}

const checkedNodes = (itemList: any) => {
  const split = purForm.value.deptIds?.split(',')
  split?.forEach((item: any) => {
    checkTree.value.push(item)

    for (const treeDataItem of itemList) {
      if (item === treeDataItem.id) {
        let p = { id: '', name: '' }
        p.id = treeDataItem.id
        p.name = treeDataItem.name
        state.selectedData.push(p)
      }
    }
  })
}

const filterAllSelected = (itemList: any) => {
  for (const item of itemList) {
    let p = { id: '', name: '' }
    p.id = item.id
    p.name = item.deptName
    state.allDepartment.push(p)
    if (item.children != null) {
      filterAllSelected(item.children)
    }
  }
}

//搜索过滤
const filterNode = (value: any, data: any) => {
  if (!value) return true
  return data.deptName.includes(value)
}

//监听输入框搜索事件
watch(filterText, (val) => {
  console.log('监听事件', val)
  treeRef.value!.filter(val)
})

//监听弹框状态变化
watch(
  () => props.dialogVisible,
  () => {
    if (!props?.dialogDetail?.id) {
      purForm.value = {}
    } else {
      purForm.value = JSON.parse(JSON.stringify(props?.dialogDetail))
      let params = { roleId: purForm.value.roleId, terminalType: 1 }
      getTreeList(params)
    }
  },
  { immediate: true }
)

const submitForm = () => {
  let deptIds: string = ''
  state.selectedData.forEach((element: any, index: number) => {
    deptIds += element.id
    if (index != state.selectedData.length - 1) {
      deptIds += ','
    }
  })
  if (deptIds == '') {
    ElMessage.warning('请选择部门')
  } else {
    emit('submit', deptIds)
  }
}

const cancel = () => {
  emit('cancel')
}

//当复选框被点击的时候触发
const checkChange = (_data: any, selectedSatate: any) => {
  state.selectedData = []
  selectedSatate.checkedKeys.forEach((keyId: any) => {
    state.allDepartment.forEach((element) => {
      if (keyId == element.id) {
        state.selectedData.push(element)
      }
    })
  })
}

//手动删除右边的条目
const deleteItem = (item: any) => {
  //删除条目,改方法会改变原数组
  state.selectedData.splice(state.selectedData.indexOf(item), 1)
  let value = treeRef.value!.getCheckedKeys(true)
  value = value.filter((valueItem: any) => valueItem != item.id)

  //设置选中属性
  treeRef.value!.setCheckedKeys(value, false)

  //因为父节点会变化,需要给右边再重新设置一次值
  let checkedKeys = treeRef.value!.getCheckedKeys(true)
  state.selectedData = []
  checkedKeys.forEach((keyId: any) => {
    state.allDepartment.forEach((element) => {
      if (keyId == element.id) {
        state.selectedData.push(element)
      }
    })
  })
}
</script>
<style scoped lang="scss">
.department {
  font-size: var(--el-font-size-base);
  .input {
    width: 80%;
  }

  .tree {
    margin-top: 20px;
  }

  .divider {
    height: 100%;
  }

  .box-selected {
    display: flex;
    flex-direction: column;
    margin-left: 20px;

    .total {
      height: 36px;
      font-weight: 400;
      line-height: 36px;
      margin-bottom: 14px;
    }

    .selected {
      display: flex;
      align-items: center;
      margin-top: 5px;

      .icon {
        margin-left: 10px;
      }
    }
  }
}
</style>
